/* eslint-disable */
import elementHelper from 'bpmn-js-properties-panel/lib/helper/ElementHelper'
import cmdHelper from 'bpmn-js-properties-panel/lib/helper/CmdHelper'
import {is} from 'bpmn-js/lib/util/ModelUtil'
import {find, forEach} from 'lodash'
import entryFactory from '../EntryFactory';
import {getNode,getBusinessObject} from "../../bpmnUtil";

/**
 * Get all camunda:property objects for a specific business object
 *
 * @param  {ModdleElement} parent
 *
 * @return {Array<ModdleElement>} a list of camunda:property objects
 */
function getPropertyValues(parent) {
  let properties = parent && getPropertiesElement(parent);
  if (properties && properties.values) {
    return properties.values;
  }
  return [];
}

/**
 * Get all camunda:Properties object for a specific business object
 *
 * @param  {ModdleElement} parent
 *
 * @return {ModdleElement} a camunda:Properties object
 */
function getPropertiesElement(element) {
  if (!isExtensionElements(element)) {
    return element.properties;
  } else {
    return getPropertiesElementInsideExtensionElements(element);
  }
}
/**
 * Get first camunda:Properties object for a specific bpmn:ExtensionElements
 * business object.
 *
 * @param {ModdleElement} extensionElements
 *
 * @return {ModdleElement} a camunda:Properties object
 */
function getPropertiesElementInsideExtensionElements(extensionElements) {
  return find(extensionElements.values, function (elem) {
    return is(elem, 'camunda:Properties');
  });
}

/**
 * Returns true, if the given business object is a bpmn:ExtensionElements.
 *
 * @param {ModdleElement} element
 *
 * @return {boolean} a boolean value
 */
function isExtensionElements(element) {
  return is(element, 'bpmn:ExtensionElements');
}





const addElement = function (setValue, currentName, element, bpmnFactory, commandC) {
  // 如果没有ExtensionElements节点，表示没有添加过额外属性
  // 创建一个新的节点，并初始化内容
  const bo = getBusinessObject(element);
  // if()
  if (!(bo && bo.get('extensionElements'))) {
    let command = []
    let parent = elementHelper.createElement('bpmn:ExtensionElements', {
      values: []
    }, element.businessObject, bpmnFactory) // 创建bpmn:ExtensionElements节点
    let cmd = cmdHelper.updateBusinessObject(element, element.businessObject, {
      extensionElements: parent
    }); // 更新element.bo节点
    command.push(cmd)

    // 创建camunda:Properties节点
    const properties = elementHelper.createElement('camunda:Properties', {}, parent, bpmnFactory)

    // 添加ExtensionElements节点
    command.push(cmdHelper.addAndRemoveElementsFromList(element, parent, 'values', 'extensionElements', [properties], []))

    // 确定property节点的属性
    let propertyProps = {}
    propertyProps.name = currentName
    propertyProps.value = setValue.value

    // 创建property节点
    let property = elementHelper.createElement('camunda:Property', propertyProps, properties, bpmnFactory)
    // 将property节点添加进入刚才创建的properties中
    command.push(cmdHelper.addElementsTolist(element, properties, 'values', [property]));

    return command
    // 如果有节点，就根据节点类型添加或修改节点
  } else {
    let parent = element.businessObject.extensionElements, // 确定父节点位置
      inx = -1 // 初始化property节点索引
    const propertys = getPropertyValues(parent) // 查找到所有的property节点集合

    forEach(propertys, function (property, index) {
      // 根据当前目标属性的名称查找到正确的property节点索引
      if (property.name === currentName) {
        inx = index
      }
    })

    if (inx === -1) {
      inx = 0
    }
    // 赋值正确的property节点
    let property = propertys[inx]

    // 如果有当前的属性节点
    if (property.name === currentName) {
      // 更新目标节点值
      return cmdHelper.updateBusinessObject(element, property, setValue)
    } else {
      // 如果没有当前的属性节点
      commandC = commandC || [];
      let properties = getPropertiesElement(parent) // 返回properties节点
      // 更新properites节点
      // commandC.push(cmdHelper.updateBusinessObject(element, parent, { 'properties': properties }))

      let propertyProps = {}
      propertyProps.name = currentName
      propertyProps.value = setValue.value
      // 创建新的Property节点
      let property = elementHelper.createElement('camunda:Property', propertyProps, properties, bpmnFactory);
      // 添加新的property节点
      commandC.push(cmdHelper.addElementsTolist(element, properties, 'values', [property]));
      return commandC
    }
  }
}

// xml内容处理
export default function addUserProps(group, element, bpmnFactory, translate) {

  const addElement1 = function(element, node) {
    var commands = [],
      parent = getParent(element, node, bo);

    if (!parent && typeof createParent === 'function') {
      var result = createParent(element, bo);
      parent = result.parent;
      commands.push(result.cmd);
    }

    var properties = getPropertiesElement(parent);
    if (!properties) {
      properties = elementHelper.createElement('camunda:Properties', {}, parent, bpmnFactory);

      if (!isExtensionElements(parent)) {
        commands.push(cmdHelper.updateBusinessObject(element, parent, { 'properties': properties }));
      } else {
        commands.push(cmdHelper.addAndRemoveElementsFromList(
          element,
          parent,
          'values',
          'extensionElements',
          [ properties ],
          []
        ));
      }
    }

    var propertyProps = {};
    forEach(modelProperties, function(prop) {
      propertyProps[prop] = undefined;
    });

    // create id if necessary
    if (modelProperties.indexOf('id') >= 0) {
      propertyProps.id = generatePropertyId();
    }

    var property = elementHelper.createElement('camunda:Property', propertyProps, properties, bpmnFactory);
    commands.push(cmdHelper.addElementsTolist(element, properties, 'values', [ property ]));

    return commands;
  }



  if (is(element, 'bpmn:UserTask') || is(element, 'bpmn:SendTask')) {


    const getRoleNams = function () {
      const roleNames = document.getElementById('camunda-adduser').getAttribute('data-roleName').split(',')
      let icons = ''
      roleNames.forEach(item => {
        icons += '<span class="icon-head" title="' + item + '">' + item.substr(0, 1) + '</span>'
      })

      return icons
    }

    const getLabel = function () {
      if (is(element, 'bpmn:SendTask')) {
        return '添加抄送人'
      } else {
        return '添加审批人'
      }
    }

    group.entries.push({
      id: 'users',
      label: getLabel(),
      modelProperty: 'user',
      set: function (element, values) {

        const openDialogElement = document.getElementById('openDialog');
        // 取到添加按钮上的roleID
        const dataRole = openDialogElement.getAttribute('data-role');
        // 取到添加按钮上的roleName
        const dataRoleNames = openDialogElement.getAttribute('data-roleName');
        const dataAssigneeType = openDialogElement.getAttribute('data-assigneeType');

        // 设置canmunda的值
        let rtn = addElement({value: dataAssigneeType}, 'assigneeType', element, bpmnFactory);
        if(dataAssigneeType === 'user'){
          rtn =  addElement({value: dataRole + '|' + dataRoleNames}, 'assigneeUserIds', element, bpmnFactory, rtn);
        }else {
          rtn =  addElement({value: dataRole }, 'assigneeRoleIds', element, bpmnFactory, rtn);
        }

        // addElement1(element,{name:'sdfs',value:'sdfsd'});
        getNode(element).updateType();
        return rtn;
      },
      get: function (element) {
        const _self = this

        // 如果有‘extensionElements’元素
        if (element.businessObject.extensionElements) {
          // 获取到propertys中的值集合
          const values = element.businessObject.extensionElements.values[0].values
          forEach(values, function (property) {
            // 如果有assigneeUserIds字段
            if (property.name === "assigneeUserIds") {
              // 绑定data-role的值
              document.getElementById('camunda-adduser').setAttribute('data-roleName', property.value.split('|')[1])

              // 添加对应的元素
              const container = document.getElementById('container')
              const RoleNameNode = getRoleNams()
              container.innerHTML = RoleNameNode
            }
          })
        }
        return {
          user: false
        }
      },
      handleClick: function (element, node, event) {
        document.getElementById('openDialog').click()
      },
      html: '<button class="add-user" data-action="handleClick" id="camunda-adduser">+</button>' +
        '<span id="container"></span>' +
        '<input type="checkbox" name="user" id="camunda-adduser-ck" style="display: none"/>'
    })


    group.entries.push(entryFactory.checkbox({
      id: 'canAssigneeChange',
      label: '审批人是否可以修改',
      modelProperty: 'canAssigneeChange',
      description: '（如勾选，则审批意见对申请人可见）',
      get(element) {

        const extensionElements = element.businessObject.extensionElements

        let val = false
        if (extensionElements) {
          let hasCAnode = false
          extensionElements.values[0].values.forEach(item => {
            if (item.name === 'canAssigneeChange') {
              hasCAnode = true
              if (item.hasOwnProperty('value')) {
                val = item.value
              }
            }
          })

          if (!hasCAnode) {
            document.getElementById('camunda-canAssigneeChange').click()
            val = true
          }
        } else {
          document.getElementById('camunda-canAssigneeChange').click()
          val = true
        }

        if (val === 'false') {
          val = false
        } else if (val === 'true') {
          val = true
        }
        return {
          canAssigneeChange: val
        }
      },
      set(element, values) {
        console.log('valuse', values)
        // return addElement({
        //   value: values.canAssigneeChange || false
        // }, 'canAssigneeChange')
      },
    }))
  }


}